import * as THREE from "three";
import pinia from '../../store/index';
import { threeViewStore } from "../../store/models/data";
let pointsArrV3: any = [];
let objArr = [];//存放绘制的模型的数组
let lineObjArr: any = [];//存放线的模型数组
let pointIndexTag = true;
let moveFlag = false;
const store = threeViewStore(pinia);

export default function height(heightVis: any) {
    let domContainer = document.getElementById("threeContainer");
    if (heightVis) {
        domContainer.style.cursor = "crosshair";
        // domContainer?.addEventListener("click", onClick);

        domContainer?.addEventListener("mousedown", onmousedown);
        window.controls.addEventListener("change", onPointerMove);
        domContainer?.addEventListener("mouseup", onClick);
        // 加载地板作为辅助射线交汇坐标点
        const loader = new THREE.TextureLoader();
        // const texture = loader.load("/img/muwen.png");
        const geometry = new THREE.BoxGeometry(10, 0.1, 10);
        // const material = new THREE.MeshBasicMaterial({ map: texture });
        const material = new THREE.MeshBasicMaterial({
            color: 0xffffff,
            // side: THREE.DoubleSide,
            transparent: true, // 设置为true，opacity才会生效
            opacity: 0.3,
        });
        const object = new THREE.Mesh(geometry, material);
        object.position.set(0, -1.5, 0);
        window.threeScene.add(object);
    }
    else {
        domContainer.style.cursor = "default";
        // domContainer?.removeEventListener("click", onClick);
        domContainer?.removeEventListener("mousemove", onMousemove);


        domContainer?.removeEventListener("mouseup", onClick);
        domContainer?.removeEventListener("mousedown", onmousedown);
        window.controls.removeEventListener("change", onPointerMove);
        // 卸载地板
    }
}

function onmousedown() {
    moveFlag = false;//如果鼠标发生了移动，就将moveFlag设置为false,则不再触发onPointerClick方法，即不再绘制点
}
function onPointerMove() {
    moveFlag = true;
}

function onClick(event: any) {
    if (!moveFlag) {
        // 如果当前是绘制的第一个点就监听触发mousemove,如果绘制的是第二个点，就结束绘制
        // 在mousemove的过程中动态计算各边数据
        if (pointsArrV3.length === 0) {
            pointIndexTag = true;
        }
        else {
            pointIndexTag = false;
        }
        if (pointIndexTag) {
            // 绘制点
            const pointer = new THREE.Vector2();
            pointer.x = (event.clientX / window.innerWidth) * 2 - 1;
            pointer.y = -(event.clientY / window.innerHeight) * 2 + 1;
            const raycaster = new THREE.Raycaster();
            raycaster.setFromCamera(pointer, window.camera);
            let position = [];
            const intersects = raycaster.intersectObjects(window.threeScene.children, true);
            if (intersects.length > 0) {
                let index = 0;
                let x = intersects[index].point.x;
                let y = intersects[index].point.y;
                let z = intersects[index].point.z;
                position.push(x);
                position.push(y);
                position.push(z);
                const vposition = intersects[0].point;
                pointsArrV3.push(vposition);
                console.log(pointsArrV3, '有点了');
                let drawpoint = drawPoint(position);
                objArr.push(drawpoint);
            }
            // 触发mousemove
            let domContainer = document.getElementById("threeContainer");
            domContainer?.addEventListener("mousemove", onMousemove);
        }
    }

}
function onMousemove(event: any) {
    if (pointIndexTag) {
        // 监听点坐标，动态绘制三条线，根据这已经画的点坐标和mousemove的坐标
        const pointer = new THREE.Vector2();
        pointer.x = (event.clientX / window.innerWidth) * 2 - 1;
        pointer.y = -(event.clientY / window.innerHeight) * 2 + 1;
        // console.log(pointer,'pointer');
        // let position = [];
        // position.push(pointer.x);
        // position.push(pointer.y);
        // position.push(pointer.z);
        const raycaster = new THREE.Raycaster();
        raycaster.setFromCamera(pointer, window.camera);
        const intersects = raycaster.intersectObjects(window.threeScene.children, true);
        if (intersects.length > 0) {
            const vposition = intersects[0].point;
            // 使用vposition作为 第二个点坐标，绘制三条边
            console.log(vposition, '移动拾取');
            // 绘制三条边，同时计算第三个点
            drawTriangle(vposition);
        }

    }
}
// 绘制点的函数
function drawPoint(position: any) {
    const geometry = new THREE.BufferGeometry();
    const color = new Float32Array([1, 0, 0]);
    // console.log(position, 'position3');
    geometry.setAttribute('position', new THREE.Float32BufferAttribute(position, 3));

    geometry.setAttribute('color', new THREE.BufferAttribute(color, 3));
    geometry.computeBoundingSphere();
    // 定义材质
    // 如果需要绘制点线可以被模型遮挡，把depthTest设置为true即可
    const material = new THREE.PointsMaterial({ size: 0.1, vertexColors: true, depthTest: false });
    const drawpoint = new THREE.Points(geometry, material);
    window.threeScene.add(drawpoint);
    return drawpoint;
}
// 绘制其余三条边和第三个点
function drawTriangle(p2Point: any) {
    // console.log(pointsArrV3[0], p2Point, '两个点');
    // 将之前的卸载掉
    if (lineObjArr.length != 0) {
        lineObjArr.forEach((item: any, index: any) => {
            window.threeScene.remove(item);
        })
    }
    let tx, ty, tz;
    let p3Point;
    if (pointsArrV3[0].y > p2Point.y) {
        ty = pointsArrV3[0].y;
        tx = p2Point.x;
        tz = p2Point.z;
        p3Point = new THREE.Vector3(tx, ty, tz);
    }
    else {
        ty = p2Point.y;
        tx = pointsArrV3[0].x;
        tz = pointsArrV3[0].z;
        p3Point = new THREE.Vector3(tx, ty, tz);
    }
    console.log(p3Point, 'p3Point');

    // 绘制线
    // 三条
    let v1v2Array = [];
    let v1v3Array = [];
    let v2v3Array = [];
    v1v2Array.push(...pointsArrV3[0]);
    v1v2Array.push(...p2Point);
    v1v3Array.push(...pointsArrV3[0]);
    v1v3Array.push(...p3Point);
    v2v3Array.push(...p2Point);
    v2v3Array.push(...p3Point);
    console.log(v1v2Array, 'v1v2Array', v1v3Array, 'v1v3Array', v2v3Array, 'v2v3Array');
    drawLine(v1v2Array);
    drawLine(v1v3Array);
    drawLine(v2v3Array);
}
// 绘制线
function drawLine(pointsArr: any) {
    const geometry = new THREE.BufferGeometry();
    const color = new Float32Array([1, 0, 0]);
    geometry.setAttribute('position', new THREE.Float32BufferAttribute(pointsArr, 3));
    geometry.setAttribute('color', new THREE.BufferAttribute(color, 3));
    geometry.computeBoundingSphere();
    const material = new THREE.LineBasicMaterial({ vertexColors: true, depthTest: false });
    const line = new THREE.Line(geometry, material);
    line.frustumCulled = false;//这行代码很关键,让屏幕外区域的点,正确显示
    window.threeScene.add(line);
    lineObjArr.push(line);
    // geometryArr.push(line);
}